package com.gradumate.server.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import com.gradumate.server.alfresco.ContentBeheer;
import com.gradumate.shared.ContentDocument;

public class VoorstelAfhandelingServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(FileUpload.class.getName());
	private static final long serialVersionUID = 8305367618713715640L;
	private ContentBeheer beheer = new ContentBeheer();

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
		
		String email = "";
		String fileName = "";
		String contenttype = "";
		String filecontents = null;

		if (ServletFileUpload.isMultipartContent(req)) {
			try {
				ServletFileUpload upload = new ServletFileUpload();
				
				
				//TODO contenttype aan de hand van de extensie setten.
				res.setContentType("text/plain"); // .txt bestand
				//res.setContentType("application/pdf"); //PDF bestand
				FileItemIterator iterator = upload.getItemIterator(req);

				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();

					log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
					if (item.isFormField()) {
						String fldvalue = Streams.asString(stream); 
						if(item.getFieldName().equals("email")){
							email = fldvalue;	
						}
					}
					else{
						fileName = item.getName();
						contenttype = item.getContentType();
						if (fileName != null) {
							fileName = FilenameUtils.getName(fileName);
						}
						try {
							filecontents = IOUtils.toString(stream);
						} finally {
							IOUtils.closeQuietly(stream);
						}
					}
				}
			} catch (Exception ex) {
				throw new ServletException(ex);
			}
		} else {
			// Voor debugging
			System.out.println("CU geen multipart");
			res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,"Formulier moet Multipart content aanleveren");
		}
		if (filecontents != null) {
			ContentDocument doc = new ContentDocument();
			doc.setTitle(fileName.replace(".txt", ""));
			doc.setSummary("Afstudeervoorstel");
			doc.setBase("cmis:document");
			doc.setType("cmis:document");
			doc.setMimetype(contenttype);
			doc.setContent(filecontents); 
			res.setStatus(HttpServletResponse.SC_ACCEPTED);
			System.out.println("email: " + email);
			System.out.println("document: " + doc.getContent());
			beheer.addDocument(doc, email);			
		} else {
			// Voor debugging
			//System.out.println("CU geen bestandsinhoud");
			res.sendError(HttpServletResponse.SC_NO_CONTENT,"Er is geen bestandsinhoud aanwezig.");	
		}
		res.flushBuffer();
	}
}